$(function () {
    findById();
})

function findById() {
    let id = sessionStorage.getItem("userId");
    let result = myAjax("/back/user/findById", {id: id})
    console.log(result);
    if (result != null) {
        setData(result.model);
    }
}

function setData(data) {
    $("#username").val(data.username);
    $("#phone").val(data.phone);
    $("#email").val(data.email);
    $("#birthday").val(data.birthday);
    // $("#age").val(data.age);
    $("input[name='sex'][value=" + data.sex + "]").attr("checked", true);
    setHobby(data.hobby);
}

function setHobby(data) {
    // let hobby = [];
    let hobby = data.replace("[", "").replace("]", "").replace(" ", "");
    let hobbys = hobby.split(",");//将字符串转换为数组
    $('input:checkbox[name="hobby"]').each(function () {
        for (let i = 0; i < hobbys.length; i++) {
            if ($(this).val() == hobbys[i]) {
                $("input:checkbox[value=" + hobbys[i] + "]").attr('checked', true);
            }
        }
    });
    // return hobby;
}

function save() {
    let data = {//key ，value
        id: sessionStorage.getItem("userId"),
        "username": $("#username").val(),
        phone: $("#phone").val(),
        email: $("#email").val(),
        sex: $('input:radio[name="sex"]:checked').val(),
        hobby: getHobby().toLocaleString(),
        birthday: $("#birthday").val()
    };
    let result = myAjax("/back/user/edit", data);
    console.log(result);
    if (result.result == "success") {
        $('.right').load('/html/back/user/userManage.html');
    } else if (result.result == "ishave") {
        alert("当前用户很受欢迎，请重新输入");
    } else {
        alert("修改失败，请重新输入");
    }

}

function getHobby() {
    let hobby = [];
    $('input:checkbox[name="hobby"]').each(function () {
        if ($(this).prop('checked')) {
            hobby.push($(this).val());
        }
    });
    return hobby;
}